<script setup lang="ts">
import myAxios from "../plugins/MyAxios.ts";
import {onMounted, ref} from "vue";
import {showFailToast, showSuccessToast} from "vant/es";
import {useRoute} from "vue-router";
import router from "../config/router.ts";
import type {TeamType} from "../models/team";

const route = useRoute();
// Initialize with empty values to avoid optional chaining in template
const addTeam = ref<TeamType>({
  teamName: '',
  description: '',
  expierTime: '',
  status: 0,
  password: ''
});

onMounted(async () => {
  const res = await myAxios.get('team/get', {
    params: {
      id: route.query.id
    }
  });
  if (res.data) {
    addTeam.value = res.data;
  }
});

const showPicker = ref(false);
const onConfirm = ({ selectedValues }: { selectedValues: string[] }) => {
  addTeam.value.expierTime = selectedValues.join('-');
  showPicker.value = false;
};

const onSubmit = async () => {
  const resp = await myAxios.post("/team/update", addTeam.value);
  if (resp.status == 0) {
    router.push({
      path: "/team",
      replace: true,
    });
    showSuccessToast("队伍修改成功");
  } else {
    showFailToast("用户修改失败");
  }
};
</script>

<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="addTeam.teamName"
          name="teamName"
          label="队伍名"
          placeholder="请输入队伍名"
          :rules="[{ required: true, message: '请填写队伍名' }]"
      />
      <van-field
          v-model="addTeam.description"
          rows="1"
          autosize
          label="描述"
          type="textarea"
          placeholder="请输入队伍描述"
      />

      <van-field
          v-model="addTeam.expierTime"
          is-link
          readonly
          name="datePicker"
          label="时间选择"
          placeholder="点击选择时间"
          @click="showPicker = true"
      />
      <van-popup v-model:show="showPicker" position="bottom">
        <van-date-picker @confirm="onConfirm" @cancel="showPicker = false"/>
      </van-popup>
      <van-field name="radio" label="队伍状态">
        <template #input>
          <van-radio-group v-model="addTeam.status" direction="horizontal">
            <van-radio :name="0">公开</van-radio>
            <van-radio :name="1">私有</van-radio>
            <van-radio :name="2">加密</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </van-cell-group>
    <van-field
        v-if="Number(addTeam.status) === 2"
        v-model="addTeam.password"
        type="password"
        name="userPassword"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
    />
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        更新
      </van-button>
    </div>
  </van-form>
</template>

<style scoped>
</style>